<template>
	<view>
		<view style="display: flex;justify-content: center;font-weight: bold;font-size: 34upx;margin-bottom: 30upx;padding-top: 20upx;"><text>云上OA办公平台</text></view>
		<view style="display: flex;justify-content: center;font-size: 32upx;">{{ nowDate }}</view>

		<u-cell-group><u-cell-item @click="toMap" icon="map" :title="address" value="查看打卡范围"></u-cell-item></u-cell-group>
		<view style="padding-left: 20upx;padding-top: 30upx;padding-bottom: 20upx;">今日打卡记录</view>
		<u-table style="width: 710upx;margin-left: 20upx;">
			<u-tr class="u-tr">
				<u-th width="38%" class="u-th">打卡类型</u-th>
				<u-th width="42%" class="u-th">打卡时间</u-th>
				<u-th width="20%" class="u-th">打卡地点</u-th>
			</u-tr>
			<u-tr class="u-tr" v-for="(item, index) in signLog" :key="index">
				<u-td width="38%" class="u-td">
					<text>
						<text v-if="index===0">有效签到</text>
						<text v-else-if="index === signLog.length-1">有效签退</text>
						<text v-else>签退</text>
						<text v-if="item.signType === 'success'" style="color: #18B566;">(正常)</text>
						<text v-if="item.signType === 'late'" style="color: #DA4C3F;">(迟到)</text>
						<text v-if="item.signType === 'early'"  style="color: #DA4C3F;">(早退)</text>
					</text>
					
				</u-td>
				<u-td width="42%" class="u-td">{{ item.signTime | time2text }}</u-td>
				<u-td width="20%" class="u-td">
					<view @click="showMapPosition(item)" style="text-decoration: underline;">
						<u-icon name="search"></u-icon>
						查看
					</view>
				</u-td>
			</u-tr>
		</u-table>

		<view style="height: 50upx;"></view>
		<view @click="sign()" style="display: flex;align-items: center;justify-content: center;flex-direction: column;">
			<view class="signBtn" :class="allowSign ? 'success' : 'danger'">
				<view>{{ nowTime || '' }}</view>
				<view v-if="allowSign">
					<text v-if="signLog.length==1">签到</text>
					<text v-else >签退</text>
				</view>
			</view>
		</view>

		<view v-if="allowSign" style="font-size: 40upx;display: flex;align-items: center;justify-content: center;height: 140upx;">
			<u-icon name="checkmark-circle-fill" color="#0ACE6F" size="50" arrow></u-icon>
			<text>您已进入打卡范围</text>
		</view>

		<view v-else style="font-size: 40upx;display: flex;align-items: center;justify-content: center;height: 140upx;">
			<u-icon name="close-circle-fill" color="#DB5145" size="50"></u-icon>
			<text>您当前不在打卡范围内</text>
		</view>

		<u-modal v-model="showModal" width="710upx" title="打卡地点">
			<view class="slot-content" style="padding-top: 20upx;"><view style="height: 600upx;" id="mapPosition"></view></view>
		</u-modal>
	</view>
</template>

<script>
import dateformat from 'dateformat';
import {
	mapState
} from "vuex"
export default {
	computed:{
		...mapState('account',['token'])
	},
	filters: {
		time2text(val) {
			if (val) {
				val = val * 1000;
				let d = new Date(val);
				return dateformat(d, 'yyyy-mm-dd HH:MM:ss');
			} else {
				return '未知';
			}
		}
	},
	data() {
		return {
			nowTime: '',
			nowDate: '',
			interval: '',
			latitude: '',
			longitude: '',
			allowSign: false,
			address: '定位中',
			times: '',
			signLog: '',
			showModal: false,
			positions: ''
		};
	},
	methods: {
		showMapPosition(item) {
			this.showModal = !this.showModal;
			this.$nextTick(() => {
				this.initMapPosition(item.lat, item.lng);
			});
		},
		initMapPosition(lat, lng) {
			var center = new TMap.LatLng(lat, lng); //设置中心点坐标
			//初始化地图
			var map = new TMap.Map('mapPosition', {
				center: center
			});

			//创建并初始化MultiMarker
			var markerLayer = new TMap.MultiMarker({
				map: map, //指定地图容器
				//样式定义
				styles: {
					//创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
					myStyle: new TMap.MarkerStyle({
						width: 25, // 点标记样式宽度（像素）
						height: 35, // 点标记样式高度（像素）

						//焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
						anchor: { x: 16, y: 32 }
					})
				},
				//点标记数据数组
				geometries: [
					{
						id: '1', //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
						styleId: 'myStyle', //指定样式id
						position: new TMap.LatLng(lat, lng), //点标记坐标位置
						properties: {
							//自定义属性
							title: 'marker1'
						}
					}
				]
			});
		},
		// 查询当天的打卡记录
		async getTodaySignLog() {
			let res = await this.$ajax.get({
				url: '/wechat/getTodaySignLog'
			});
			let today = new Date().getTime();
			today = dateformat(today,"yyyy/mm/dd")
			
			let start = this.times.StartTime;
			start = start.substr(0,8);
		 
			let end = this.times.EndTime;
			end = end.substr(0,8);
			
			if(res.data.length){
				// 获取上班时间的 时间戳
				let startTime = today + " " + start;
				let startTimeStamp = new Date(startTime).getTime();
				// 判断第一次打卡时间是否小于 此时间戳
				if(res.data[0].signTime*1000 < startTimeStamp){
					res.data[0].signType = 'success'
				}else{
					res.data[0].signType = 'late'
				}
			}
			
			if(res.data.length>=2){
				// 获取下班的时间戳
				let endTime = today + " " + end;
				let endTimeStamp = new Date(endTime).getTime();
				if(res.data[res.data.length-1].signTime*1000 > endTimeStamp){
					res.data[res.data.length-1].signType = 'success'
				}else{
					res.data[res.data.length-1].signType = 'early'
				}
			}
			this.signLog = res.data;
		},

		toMap() {
			console.log(this.positions);
			uni.setStorageSync('signPositions', this.positions);

			uni.navigateTo({
				url: `/pages/oa/sign-map/sign-map?lat=${this.latitude}&lng=${this.longitude}`
			});
		},
		// 经纬度转地理位置
		position2address(lat, lng) {
			this.$ajax
				.get({
					url: `/wechat/position2address?lat=${lat}&lng=${lng}`
				})
				.then(res => {
					this.address = res.data;
				});
		},
		sign() {
			if (this.allowSign) {
				this.$store
					.dispatch('account/sign', {
						latitude: this.latitude || '34.1234',
						longitude: this.longitude || '108.1234'
					})
					.then(res => {
						uni.showModal({
							title: '系统提示',
							content: '打卡成功',
							showCancel: false,
							confirmText: '回到首页',
							success() {
								uni.reLaunch({
									url: '/pages/oa/person/person'
								});
							}
						});
					});
			}
		},
		async refreshPosition() {
			let positions = await this.$store.dispatch('account/getSignPosition');
			positions = positions.data;
			this.times = positions.time;
			this.getTodaySignLog();
			if(this.times.TypeCode!='0'){
				uni.showModal({
					title:"系统提示",
					content:"今日为"+this.times.TypeName + "确定打卡吗？",
					cancelText:"回到首页",
					confirmText:"继续打卡",
					success(res) {
						if(!res.confirm){
							uni.reLaunch({
								url:"/pages/oa/person/person"
							})
						}
					}
				})
			}
			this.positions = positions.position;
			wxjs.getLocation({
				type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
				success: res => {
					console.log('定位成功---->');
					console.log(res);

					this.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
					this.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
					this.position2address(this.latitude, this.longitude);
					// 判断是否在打卡范围内
					// console.log("判断是否在打卡范围内")
					// console.log(this.positions)
					for (let i = 0; i < this.positions.length; i++) {
						let p = this.positions[i];
						// console.log(p)
						var pos = new TMap.LatLng(this.latitude, this.longitude);
						// console.log(pos)
						let path = [
							new TMap.LatLng(p.LeftTopLat, p.LeftTopLon),
							new TMap.LatLng(p.RightTopLat, p.RightTopLon),
							new TMap.LatLng(p.RightBottomLat, p.RightBottomLon),
							new TMap.LatLng(p.LeftBottomLat, p.LeftBottomLon)
						];
						// console.log(path)
						// 判断点是否在多边形内
						// console.log(TMap)
						var isIn = TMap.geometry.isPointInPolygon(pos, path);
						// console.log("isIn",isIn)
					 
						 
						if (isIn) {
							this.allowSign = true;
							break;
						}else{
							// console.log("不在")
						}
					}

					// this.allowSign = true;
				},
				fail(err) {
					console.log(err);
				}
			});
		},
		refreshTime() {
			// console.log('refreshTime');
			this.nowTime = this.$u.timeFormat(new Date().getTime(), 'hh:MM:ss');
		}
	},
	onLoad() {
		
		setTimeout(()=>{
			if(!this.token){
				uni.showModal({
					title:"系统提示",
					content:"您还未登录或登录已过期",
					showCancel:false,
					confirmText:"重新授权",
					success() {
						window.location.href = "http://zsoa.gek6.com/index.php/wechat/wxlogin"
					}
				})
			}else{
				this.nowDate = this.$u.timeFormat(new Date().getTime(), 'yyyy年mm月dd日');
				
				this.refreshTime();
				this.interval = setInterval(() => {
					this.refreshTime();
				}, 1000);
				uni.showLoading({
					title: '定位中'
				});
				this.refreshPosition();
				setTimeout(() => {
					uni.hideLoading();
				}, 3000);
			}
		},500)
		
		

		
	},
	destroyed() {
		clearInterval(this.interval);
	}
};
</script>

<style lang="scss">
.signBtn {
	width: 300upx;
	height: 300upx;
	border-radius: 50%;

	color: #ffffff;
	font-size: 34upx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
}
.signBtn.success {
	background-color: #1a9e34;
	-webkit-animation: ani 2s linear infinite;
}
.signBtn.danger {
	background-color: #db5045;
	opacity: 0.7;
	-webkit-animation: ani2 2s linear infinite;
}

@keyframes ani2 {
	0% {
		box-shadow: 0 0 4px #db5045;
	}
	25% {
		box-shadow: 0 0 10px #db5045;
	}
	50% {
		box-shadow: 0 0 20px #db5045;
	}
	75% {
		box-shadow: 0 0 10px #db5045;
	}
	100% {
		box-shadow: 0 0 4px #db5045;
	}
}

@keyframes ani {
	0% {
		box-shadow: 0 0 4px #1a9e34;
	}
	25% {
		box-shadow: 0 0 10px #1a9e34;
	}
	50% {
		box-shadow: 0 0 20px #1a9e34;
	}
	75% {
		box-shadow: 0 0 10px #1a9e34;
	}
	100% {
		box-shadow: 0 0 4px #1a9e34;
	}
}

.u-card-wrap {
	background-color: $u-bg-color;
	padding: 1px;
}

.u-body-item {
	font-size: 32rpx;
	color: #333;
	padding: 20rpx 10rpx;
}

.u-body-item image {
	width: 120rpx;
	flex: 0 0 120rpx;
	height: 120rpx;
	border-radius: 8rpx;
	margin-left: 12rpx;
}
</style>
